package com.yi.wood.web.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author MoYi
 * Created time 2019/4/12 10:21
 * 接口调用日志
 */
@Log4j2
@Aspect
@Component
public class WebRequestLogPoint {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void mappingCut(){
    }

    @Around("mappingCut()")
    public Object before(ProceedingJoinPoint jp) throws Throwable {
        Long startTime = System.currentTimeMillis();
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();

        String postMethod = "post";
        Signature signature = jp.getSignature();
        String className = signature.getDeclaringTypeName();
        String methodName = signature.getName();
        String token = request.getHeader("Wood-Token");
        log.info("请求开始------------token={}------------",token);
        if (!postMethod.equalsIgnoreCase(method)){
            log.info(" => {}->{}() URI: {}, method: {}, params: {}",className, methodName, uri, method, queryString);
        }else {
            log.info(" => {}->{}() URI: {}, method: {}, body: {}",className, methodName, uri, method, JSON.toJSONString(jp.getArgs()));
        }

        Object result = jp.proceed();
        Long endTime = System.currentTimeMillis();
        log.info(" => {}->{}(), URI: {}, method: {}", className, methodName, uri, method);
        log.info("请求结束------------useTime={}------------",((endTime - startTime)+"ms"));

        return result;
    }

}